from flask import Blueprint, render_template, request, redirect, url_for, g
from exts import db
from models import Exam, studentModel, Student_Exam, stuAns
# 这里定义的权限视图函数url前缀为"/exam"
bp = Blueprint("exam", __name__, url_prefix="/exam")


@bp.route('/exam_register', methods=['GET', 'POST'])
def examRegister():
    exams = Exam.query.all()
    id = g.user.id
    stu = studentModel.query.get(id)
    signed = set()
    for asso in stu.exams:
        signed.add(Exam.query.get(asso.exam_id).id)
    print(signed)
    # 如果这个考试报了名，为1,否则为0
    exam_list = []
    for exam in exams:
        exam_list.append((exam, 1 if exam.id in signed else 0))
    return render_template("examRegister.html", exam_list=exam_list)


@bp.route('/infoConfirm/<int:exam_id>', methods=['GET', 'POST'])
def infoConfirm(exam_id):
    # TODO 可以修改信息
    id = g.user.id
    stu = studentModel.query.get(id)
    if request.method == 'GET':
        return render_template('infoConfirm.html', stu=stu)
    else:
        exam = Exam.query.get(exam_id)
        a = Student_Exam()
        a.exam = exam
        stu.exams.append(a)
        db.session.commit()
        return redirect(url_for('stu.stuIndex'))


@bp.route('/doExam/<int:exam_id>', methods=['GET', 'POST'])
def do_exam(exam_id):
    cur_exam = Exam.query.get(exam_id)
    questions = cur_exam.questions
    ss_ctx = []
    multi = []     # 填空
    short_ans = []      # 简答
    if request.method == 'GET':
        for question in questions:
            if question.question_type == 0:
                tmp = question.ctx.split('|')
                ss_ctx.append((tmp[0], tmp[1:], question.id))
            elif question.question_type == 1:
                tmp = question.ctx.split('|')
                multi.append((tmp[0], tmp[1:], question.id))
            else:
                short_ans.append((question.ctx, question.id))
        return render_template('doExam.html',
                               exam=cur_exam, ss_ctx=ss_ctx,
                               multi=multi, short_ans=short_ans)
    else:
        # 单选和多选自动判分
        # 答对给4分
        cur_score = 0
        for question in questions:
            answer = request.form.get(str(question.id))
            # TODO 添加多选自动判卷
            flag = question.question_type == 0
            if flag and answer == question.correct_ans:
                cur_score += 4
            # 添加学生简答题的回答
            if question.question_type == 2:
                stu_ans = stuAns(stu_id=g.user.id, exam_id=exam_id, question_id=question.id,
                                 ans=answer)
                db.session.add(stu_ans)
                db.session.commit()
        # 拿到对应的考试信息
        asso = Student_Exam.query.filter_by(
            exam_id=exam_id, stu_id=g.user.id).first()
        asso.score = cur_score
        # 更新状态为考完试
        asso.finished = '1'
        db.session.commit()
        return redirect(url_for('stu.stuIndex'))
